package com.bbseguros.pesquisador.converter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;

/**
 * @author hmsilva
 * 
 */
public class HttpWebService {

	private static Logger logger = Logger.getLogger(HttpWebService.class);

	private String URL = "http://localhost:9080";
	private String service = "";
    private StringBuffer parameters = null;
    
    public static final String CONTEXT_SEPARATOR = "/";
    
    public HttpWebService(String url) {		
        super();
        this.URL = url;
        parameters = new StringBuffer();
    }
      	
    public void setParam(String key, String value) {
        parameters.append(key);
        parameters.append("=");
        parameters.append(value);
        parameters.append("&");
    }
    
    public String getPostParams() {
        String params = parameters.toString();   
                
        if(params.length() > 0){
            return params.substring(0, params.length() - 1);
   		}
        
    	return params;
    }    
    
    public void setService(String service){
    	if(service.indexOf(CONTEXT_SEPARATOR) <= -1){
    		service = CONTEXT_SEPARATOR + service;
    	}
    	this.service = service;
    }
    
    public void clearParameters(){
    	this.parameters = new StringBuffer();
    	
    }
    
    /**
     * @return
     * @throws Exception
     */
    public String sendReceive() throws Exception{
    	logger.debug("[IN]");
    	
    	String ret = "";
    	StringBuffer buffer = new StringBuffer();
    	
		try {			
			logger.debug("[URL: "+URL+service+"]");
			URL url = new URL( (URL + service) );
			URLConnection conn = url.openConnection();
				
			conn.setDoOutput(true);
	         
	        byte[] data = getPostParams().getBytes();
	        
	        conn.setRequestProperty("Host", "localhost");
	        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");	        
	        conn.setRequestProperty("Content-Length", Integer.toString(data.length));
	        
	        conn.getOutputStream().write(data);
	        conn.getOutputStream().close();
	        
	        logger.debug("[SEND OK]");
	        
	        byte[] retorno = getOutput(conn.getInputStream());			
	        buffer.append(new String(retorno));
            
            logger.debug("[RECEIVED OK] RETORNO: "+buffer.toString());
            
		} catch (MalformedURLException e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e);
			
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e);
		}
        
		ret =  buffer.toString();
		
		ret.replaceAll("&lt;", "<");
        ret.replaceAll("&gt;", ">");
        ret.replaceAll("&#13;", "");
		
		logger.debug("[OUT] "+ret);
		return ret;
    }
    
	/**
	 * @param input
	 * @return
	 * @throws IOException
	 */
	private byte[] getOutput(InputStream input) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		byte[] r = new byte[512];
		int c = 0;
		while (((c = input.read(r, 0, r.length)) != -1)) {
		    baos.write(r, 0, c);
		}
		baos.flush();
		return baos.toByteArray();
	}
    
}